<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园BBS</title>
    <link rel="icon" href="../assets/QQ.ico">
    <!--element-ui的样式-->
    <link rel="stylesheet" href="../plugins/element-ui/index.css"/>
    <!-- 引入样式  -->
    <link rel="stylesheet" href="../css/detail.css"/>
    <link rel="stylesheet" href="../css/base.css">
</head>

<body>
<div id="app">
    <div id="header">
        <div class="title">校园BBS系统</div>
        <div class="login" id="header-login">
            <div v-if="!isLogin">
                您尚未
                <a href="login.html">登录</a>
            </div>
            <div v-else="isLogin"
                 style="display: flex;justify-content: center;flex-direction: column; align-items: flex-start;font-size: 15px;line-height: 25px;">
                <div style="display: flex;justify-content: center;align-items: center;">头像:<img :src="imgUrl"
                                                                                                  style="width: 50px;height: 50px;border-radius: 50%;margin-left: 20px"></img>
                </div>
                <div style="display: flex;justify-content: center;align-items: center;">用户名:<span
                        style="font-size: 1.5rem;color: #f56c6c;margin-left: 20px;">{{userInfo.userName}}</span></div>
                <a @click="logout" id="logout">退出登录</a>
            </div>
        </div>
    </div>
    <div class="body">
        <div class="path">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item v-for="item in topTitle" :key="item.priority"><a :href="item.url">{{item.title}}</a>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="content">
            <div class="content-header">
                <p>本页主题：<span>{{topicInfo.title}}</span></p>
            </div>
            <hr style="width:100%">
            <div class="content-wrapper">
                <div class="content-body" v-show="isFirstPage">
                    <div class="user-info">
                        <span>{{topicInfo.userInfo.userName}}</span>
                        <img :src="topicInfo.userInfo.userImg">
                        <p>注册时间: <span>{{topicInfo.userInfo.createdTime}}</span></p>
                    </div>
                    <div class="article">
                        <span style="line-height: 50px"><p style="color: black;font-size: 2rem;font-weight: bold">{{topicInfo.title}}</p></span>
                        <span style="line-height: 20px"><p style="color: black;font-size: 1.25rem;font-family: cursive">{{topicInfo.content}}</p></span>
                        <div class="articleTime">
                            <span>发表时间:{{topicInfo.createTime}}</span>
                            <span>修改时间:{{topicInfo.updateTime}}</span>
                            <div class="agree">
                                <span>获赞数: <span style="font-weight: bolder">{{topicInfo.agree}}</span></span>
                            </div>
                        </div>
                    </div>
                    <div class="edit-button">
                        <el-tooltip effect="dark" content="回复/编辑" placement="left">
                            <el-button type="primary" :icon="replyORedit" circle v-show="isEdit"
                                       @click="ReplyOrEdit"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="打开/关闭功能盒子" placement="left">
                            <el-button type="info" :icon="topicOpenOrClose" circle @click="changeEditState"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="点赞(暂未开发)/删除" placement="left">
                            <el-button type="primary" :icon="agreeORdelete" circle v-show="isEdit"
                                       @click="AgreeOrDelete"></el-button>
                        </el-tooltip>
                    </div>
                </div>
                <el-divider content-position="center">往下是回复内容~~~</el-divider>

                <div class="content-body" v-for="(user,index) in userArticle" :key="index">
                    <div class="user-info">
                        <span>{{user.userInfo.userName}}</span>
                        <img :src="user.userInfo.userImg">
                        <p>注册时间: <span>{{user.userInfo.createdTime}}</span></p>
                    </div>
                    <div class="article">
                        <span style="line-height: 50px"><p style="color: black;font-size: 2rem;font-weight: bold">{{user.title}}</p></span>
                        <span style="line-height: 20px"><p style="color: black;font-size: 1.25rem;font-family: cursive">{{user.content}}</p></span>
                        <div class="articleTime">
                            <span>发表时间:{{user.createdTime}}</span>
                            <span>修改时间:{{user.updateTime}}</span>
                            <div class="agree">
                                <span>获赞数: <span style="font-weight: bolder">{{topicInfo.agree}}</span></span>
                            </div>
                        </div>
                    </div>
                    <div class="edit-button">
                        <el-tooltip effect="dark" content="回复/编辑" placement="left">
                            <el-button type="primary" :icon="user.replyORedit" circle v-show="user.isEdit"
                                       @click="ReplyOrEdit(null,`${index}`)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="打开/关闭功能盒子" placement="left">
                            <el-button type="info" :icon="user.openOrClose" circle
                                       @click="changeEditState(null,`${index}`)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="点赞(暂未开发)/删除" placement="left">
                            <el-button type="primary" :icon="user.agreeORdelete" circle v-show="user.isEdit"
                                       @click="AgreeOrDelete(null,`${index}`)"></el-button>
                        </el-tooltip>
                    </div>
                </div>

                <el-dialog title="编辑" :visible.sync="showEditForm">
                    <el-form :model="editForm">
                        <el-form-item label="标题">
                            <el-input v-model="editForm.title" maxlength="50" minlength="5" show-word-limit :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="内容">
                            <el-input v-model="editForm.content" type="textarea" autosize :rows='2' show-word-limit
                                      maxlength="9999"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="showEditForm = false">取 消</el-button>
                        <el-button @click="clearEditForm">清 空</el-button>
                        <el-button type="primary" @click="submitEditForm">确 定</el-button>
                    </div>
                </el-dialog>
                <el-dialog title="回复" :visible.sync="showReplyForm">
                    <el-form :model="replyForm">
                        <el-form-item label="标题">
                            <el-input v-model="replyForm.title" maxlength="50" minlength="5"
                                      :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="内容">
                            <el-input v-model="replyForm.content" type="textarea" autosize :rows='2' show-word-limit
                                      maxlength="9999"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="showReplyForm = false">取 消</el-button>
                        <el-button @click="clearReplyForm">清 空</el-button>
                        <el-button type="primary" @click="submitReplyForm">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="content-page">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :page-sizes="[2,5, 10, 20, 50,100]" :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper" :total="passageCount"
                               :current-page="currentPage">
                </el-pagination>
            </div>
        </div>
    </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../plugins/vue.js"></script>
<!-- 引入组件库 -->
<script src="../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../plugins/axios.min.js"></script>
<script src="../js/request.js"></script>
<script src="../api/detail.js"></script>
<script src="../api/base.js"></script>
</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                isLogin: false,
                isEdit: false,
                showEditForm: false,
                showReplyForm: false,
                editForm: {
                    title: '',
                    content: ''
                },
                replyForm: {
                    content: ''
                },
                temp: '',
                pageSize: 2,
                replyORedit: '',
                agreeORdelete: '',
                currentPage: 1,
                passageCount: 0,
                userInfo: {},
                topTitle: [
                    {
                        title: '首页',
                        url: 'index.html',
                        priority: '1'
                    },
                    {
                        title: '',
                        url: 'list.html',
                        priority: '2'
                    },
                    {
                        title: '',
                        url: 'detail.html',
                        priority: '3'
                    }
                ],
                userArticle: [],
                topicInfo: {
                    userInfo: {}
                }
            }
        },
        computed: {
            topicOpenOrClose() {
                if (this.isEdit) {
                    return 'el-icon-close'
                } else {
                    return 'el-icon-menu'
                }
            },
            isFirstPage() {
                if (this.currentPage === 1) {
                    return true
                }
                return false
            },
        },
        created() {
            this.init()
        },
        methods: {
            async init() {
                const userInfo = localStorage.getItem('userInfo')
                let boardName = localStorage.getItem("boardName")
                let topicName = localStorage.getItem("topicName")
                let topicId = localStorage.getItem("topicId")

                //初始化用户信息
                let user = JSON.parse(userInfo)
                if (user != null) {
                    this.isLogin = true
                    this.userInfo = user
                    this.imgUrl = `/common/download?name=${this.userInfo.head}`
                }
                //初始化标题信息
                for (const t of this.topTitle) {
                    if (t.priority === '2') {
                        t.title = boardName
                    }
                }
                //初始化主题信息
                for (const t of this.topTitle) {
                    if (t.priority === '3') {
                        t.title = topicName
                    }
                }
                await getTopicInfoApi(topicId).then(res => {
                    if (String(res.code) === '1') {
                        this.editTopic(res.data)
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })

                //初始化回复消息
                const params = {
                    page: this.currentPage,
                    pageSize: this.pageSize,
                }
                // this.userArticle = []
                await getReplyInfoApi(topicId, params).then(res => {
                    if (String(res.code) === '1') {
                        this.editTable(res.data.records)
                        this.passageCount = (res.data.total)
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })

                this.userArticle.forEach(item => {
                    item.replyORedit= ''
                    item.agreeORdelete = ''
                    item.openOrClose = 'el-icon-menu'
                    item.isEdit = false
                })


            },
            async logout() {
                await logoutApi().then((res) => {
                    if (res.code === 1) {
                        localStorage.removeItem('userInfo')
                        window.location.href = 'login.html'
                    }
                })
            },
            editTable(all) {
                this.userArticle = []
                for (const item of all) {
                    let temp = {}
                    temp.replyId = item.id
                    temp.title = item.title
                    temp.content = item.content
                    temp.agree = item.agree
                    temp.createdTime = item.createTime
                    temp.updateTime = item.updateTime
                    temp.userInfo = this.getUserInfo(item.userId).then(res => {
                        temp.userInfo = res
                    })
                    this.userArticle.push(temp)
                }
            },
            async getUserInfo(userId) {
                let temp = {}
                let userInfo = {}
                await getUserInfoApi(userId).then(res => {
                    this.temp = res.data
                })
                userInfo.userId = this.temp.id
                userInfo.userName = this.temp.userName
                userInfo.userImg = `/common/download?name=${this.temp.head}`
                userInfo.createdTime = this.temp.createTime
                return userInfo
            },
            handleSizeChange(size) {
                this.pageSize = size
                this.init()
            },
            handleCurrentChange(currentPage) {
                this.currentPage = currentPage
                this.init()
            },
            editTopic(item) {
                temp = {}
                temp.title = item.title
                temp.content = item.content
                temp.agree = item.agree
                temp.createTime = item.createTime
                temp.updateTime = item.updateTime
                temp.userInfo = this.getUserInfo(item.userId).then(res => {
                    temp.userInfo = res
                })
                this.topicInfo = temp
            },
            changeEditState(event, index) {

                if (index != null) {
                    if (this.userArticle.at(index).userInfo.userId === this.userInfo.id){
                        this.userArticle.at(index).replyORedit = 'el-icon-edit-outline'
                        this.userArticle.at(index).agreeORdelete = 'el-icon-delete'
                    }else{
                        this.userArticle.at(index).replyORedit = 'el-icon-chat-dot-square'
                        this.userArticle.at(index).agreeORdelete = 'el-icon-star-off'
                    }
                    if (this.userArticle.at(index).isEdit){
                        this.userArticle.at(index).openOrClose = 'el-icon-menu'
                    }else{
                        this.userArticle.at(index).openOrClose = 'el-icon-close'
                    }
                    this.userArticle.at(index).isEdit = !this.userArticle.at(index).isEdit
                } else {
                    if (this.topicInfo.userInfo.userId === this.userInfo.id){
                        this.replyORedit = 'el-icon-edit-outline'
                        this.agreeORdelete = 'el-icon-delete'
                    }else{
                        this.replyORedit = 'el-icon-chat-dot-square'
                        this.agreeORdelete = 'el-icon-star-off'
                    }
                    this.isEdit = !this.isEdit
                }
                this.$forceUpdate();
            },
            ReplyOrEdit(event, index) {
                if (index != null) {
                    this.temp.ID = this.userArticle.at(index).replyId
                    this.temp.state = 'reply'
                    if (this.isReplyUser(index)) {
                        //编辑
                        this.getEditFormInfo(index)
                        this.showEditForm = true
                    } else {
                        //回复
                        this.getReplyFormInfo(index)
                        this.showReplyForm = true
                    }
                } else {
                    this.temp.ID = localStorage.getItem("topicId")
                    this.temp.state = 'topic'
                    if (this.isTopicUser()) {
                        //编辑
                        this.getTopicEditFormInfo()
                        this.showEditForm = true
                    } else {
                        //回复
                        this.getTopicReplyFormInfo()
                        this.showReplyForm = true
                    }
                }
            },
            isTopicUser() {
                if (this.userInfo.id === this.topicInfo.userInfo.userId) {
                    return true
                }
                return false
            },
            isReplyUser(index) {
                if (this.userInfo.id === this.userArticle.at(index).userInfo.userId) {
                    return true
                }
                return false
            },
            clearReplyForm() {
                // this.replyForm.title = ''
                this.replyForm.content = ''
            },
            clearEditForm() {
                // this.editForm.title = ''
                this.editForm.content = ''
            },
            getTopicEditFormInfo() {
                this.editForm.title = this.topicInfo.title
                this.editForm.content = this.topicInfo.content
            },
            getTopicReplyFormInfo() {
                this.replyForm.title = this.topicInfo.content
            },
            getEditFormInfo(index) {
                this.editForm.title = this.userArticle.at(index).title
                this.editForm.content = this.userArticle.at(index).content
            },
            getReplyFormInfo(index) {
                this.replyForm.title = this.userArticle.at(index).content
            },
            async submitEditForm() {
                data = this.editForm
                if (this.temp.state === 'topic') {
                    //主题
                    data.id = this.temp.ID
                    await editTopic(data).then(res => {
                        if (String(res.code) === '1') {
                            this.$message({
                                message: `${res.data}`,
                                type: 'success'
                            })
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                } else {
                    //回复
                    data.id = this.temp.ID
                    await editReply(data).then(res => {
                        if (String(res.code) === '1') {
                            this.$message({
                                message: `${res.data}`,
                                type: 'success'
                            })
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                }
                this.showEditForm = false
                this.clearEditForm()
                this.init()
            },
            async submitReplyForm() {
                data = this.replyForm
                if (this.temp.state === 'topic') {
                    data.topicId = this.temp.ID
                    await addReply(data).then(res => {
                        if (String(res.code) === '1') {
                            this.$message({
                                message: `${res.data}`,
                                type: 'success'
                            })
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                } else {
                    data.rereplyId = this.temp.ID
                    await addReply(data).then(res => {
                        if (String(res.code) === '1') {
                            this.$message({
                                message: `${res.data}`,
                                type: 'success'
                            })
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                }
                this.showReplyForm = false
                this.clearReplyForm()
                this.init()
            },
            AgreeOrDelete(event, index) {
                if (index != null) {
                    if (this.isReplyUser(index)) {
                        //删除
                        this.$confirm('此操作将永久删除该文章,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            replyId = this.userArticle.at(index).replyId
                            this.deleteReply(replyId)
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消删除'
                            });
                        });

                    } else {
                        //点赞
                        // 暂未开发

                    }
                } else {
                    if (this.isTopicUser()) {
                        //删除
                        this.$confirm('此操作将永久删除该文章,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            topicId = localStorage.getItem('topicId')
                            this.deleteTopic(topicId)
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消删除'
                            });
                        });

                    } else {
                        //点赞
                        // 暂未开发

                    }
                }
            },
            async deleteReply(replyId) {
                await deleteReplyApi(replyId).then(res => {
                    if (String(res.code) === '1') {
                        this.$message({
                            message: `${res.data}`,
                            type: 'success'
                        })
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
                this.init()
            },
            async deleteTopic(topicId) {
                await deleteTopicApi(topicId).then(res => {
                    if (String(res.code) === '1') {
                        this.$message({
                            message: `${res.data}`,
                            type: 'success'
                        })
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
                window.open("list.html", "_self")
            }
        }

    })
</script>

</html>